iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
Software Development

iOS 學習筆記系列 第 24

Day24 URLSession 04 - DELETE

  • 分享至 

  • xImage
  •  

DELETE:刪除資料

同樣根據以上的Reqres API 來示範

DELETE api 執行後只有status code 來判斷是否刪除成功,故不需要建一個model 來接response

我們在UserURLSession.swift處理關於URLSession的事件

    func userDeleteRequest(id: Int, completionHandler: @escaping (String) -> Void) {
        
        let url = URL(string: "https://reqres.in/api/users/\(id)")!
        var request = URLRequest(url: url)
        request.httpMethod = "DELETE"
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            var statusCode = -1
            if let httpResponse = response as? HTTPURLResponse {
                statusCode = httpResponse.statusCode
            }
            if(statusCode == 204){
                completionHandler("DELETE Success")
            }else{
                completionHandler("DELETE Fail")
            }
        }.resume()
    }

之後在View 設計畫面並使用
DELETESampleView.swift

import SwiftUI

struct DELETESampleView: View {
    @State private var response = ""

    var body: some View {
        NavigationView {
            VStack {
                
                Button {
                    UserURLSession.shared.userDeleteRequest(id: 2) { response in
                        DispatchQueue.main.async {
                            self.response = response
                        }
                    }

                } label: {
                    Text("DELETE Request")
                }
                Text("response: \(response)")
     }
            .navigationBarTitleDisplayMode(.inline)
            .navigationTitle(Text("URLSession DELETE Sample"))
        }
    }
}

struct DELETESampleView_Previews: PreviewProvider {
    static var previews: some View {
        DELETESampleView()
    }
}

這邊所有URLSession 的範例一起放在Github: URLSessionSample 供大家參考


上一篇
Day23 URLSession 03 - PUT / PATCH
下一篇
Day25 Data Storage in iOS 01 - UserDefaults
系列文
iOS 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言